package com.yantong.controller.finance;

import com.yantong.annotation.Log;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.service.ConfigService;
import com.yantong.pojo.WorkOrder;
import com.yantong.service.WorkOrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 财务工单控制类
 * @author kanghaixin
 * @date 2018/9/6.19:27
 */

@Controller
@RequestMapping("/finance/workorder")
public class FinanceWorkOrderController extends BaseController {
    private static final String prefix = "finance/workorder";
    private static final Logger logger = LoggerFactory.getLogger(FinanceWorkOrderController.class);
    @Autowired
    private ConfigService configService;
    @Autowired
    private WorkOrderService workOrderService;

    /**
     * 财务工单列表
     * @param model
     * @return
     */
    @RequiresPermissions("finance:workorder:workorder")
    @GetMapping()
    public String financeWorkOrder(Model model) {
        model.addAttribute("imgPrefix", configService.getImgPrefix());
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/financeOrders";
    }

    /**
     * 财务工单列表
     * @param queryItem
     * @param status
     * @param start
     * @param end
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @RequiresPermissions("finance:workorder:workorder")
    @GetMapping("/list")
    public PageUtils<WorkOrder> listFinanceWorkOrders(String queryItem, Integer status, Long centreId, String start, String end, int offset, int limit) {
        return workOrderService.listFinanceWorkOrders(queryItem, status, centreId,DateUtils.parseDateForm(start), DateUtils.parseDateForm(end), offset, limit);
    }


    /**
     * 工单导出
     * @param queryItem
     * @param status
     * @param centreId
     * @param start
     * @param end
     * @param response
     */
    @RequiresPermissions("finance:workorder:export")
    @GetMapping("/export")
    public void exportWorkOrders(String queryItem, Integer status, Long centreId, Date start, Date end, HttpServletResponse response) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"工单号", "门店姓名", "门店ID", "门店手机","上级门店", "上级门店ID","工单内容","评估客服","订单区域",
                "售后数量","责任方", "工单类型", "工单原因", "订单编号","商品信息","上架时间段", "供应商","成本价", "应付价",
                "运送车次", "下单信息","微信退款","余额退款","总退款","佣金","申请时间", "操作财务", "操作时间"};
        resultData.add(0, Arrays.asList(head));
        List<WorkOrder> list = workOrderService.listFinanceWorkOrders(queryItem,status,centreId, start, end);
        if (CollectionUtils.isNotEmpty(list)) {
            for (WorkOrder wo: list) {
                if (wo == null) {
                    continue;
                }
                List<Object> row = new ArrayList<>();
                row.add(wo.getWorksn());
                row.add(wo.getRealname());
                row.add(wo.getMid());
                row.add(wo.getMobile());
                row.add(wo.getUpRealname());
                row.add(wo.getUpMid());
                row.add(wo.getContents());
                row.add(wo.getKefuname());
                row.add(wo.getCity());
                row.add(wo.getNums());
                row.add(StringUtils.isEmpty(wo.getResponse())?"供应商":wo.getResponse());
                row.add(wo.getTypename());
                row.add(wo.getCause());
                row.add(wo.getOrdersn());
                row.add("商品编号:"+ wo.getGoodscode()+ "商品名称:"+ wo.getShortTitle()+ "成本价:"+ wo.getCostprice()+
                        "应付价:"+ wo.getMarketprice() + "数量:"+ wo.getTotal()+ "总价:"+ wo.getPrice());
                row.add(DateUtils.formatFull(wo.getUpStartTime()) + "--"+ DateUtils.formatFull(wo.getUpEndTime()));
                row.add(wo.getSupplyName());
                row.add(wo.getCostprice());
                row.add(wo.getMarketprice());
                row.add(wo.getCarName());
                row.add("送货地址:"+ wo.getSaddress()+ "下单人:" + wo.getNickname()+ "收货人:"+ wo.getSname()+ "手机号:"+ wo.getsMobile());
                row.add(wo.getPaymoney());
                row.add(wo.getCredit2money());
                row.add(wo.getMoney());
                row.add(wo.getCommissionMoney());
                row.add(DateUtils.formatFull(wo.getCreateTime()));
                row.add(wo.getCaiwuname());
                row.add(DateUtils.formatFull(wo.getPaytime()));
                resultData.add(row);
            }
        }
        String fileName = "财务工单_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
        try {
            ExcelHelper.exportExcel(response, fileName, "财务工单", resultData);
        } catch (IOException e) {
            logger.info("export finance workOrder error:{}", e.getMessage());
        }
    }

    /**
     * 财务拒绝页面
     * @param workId
     * @param model
     * @return
     */
    @RequiresPermissions("finance:workorder:refuse")
    @GetMapping("/refuseWorkOrder/{workId}")
    public String refuseWorkOrder(@PathVariable Long workId, Model model) {
        model.addAttribute("workId", workId);
        return prefix + "/refuseWork";
    }

    /**
     * 财务拒绝工单操作
     * @param workId
     * @param content
     * @return
     */
    @Log(module = "财务工单管理", operation = "财务拒绝")
    @ResponseBody
    @PostMapping("/refuseWork")
    @RequiresPermissions("finance:workorder:refuse")
    public ResultVo refuseWork(Long workId, String content) {
        if (workId == null || StringUtils.isEmpty(content)) {
            return ResultVo.error();
        }
        WorkOrder workOrder = new WorkOrder();
        workOrder.setId(workId);
        workOrder.setCaiwuname(getNikeName());
        workOrder.setCaiwuid(getUserId());
        workOrder.setCaiwuContents(content);
        if (workOrderService.financeRefuseWork(workOrder)< 1){
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
    /**
     * 回复查看页面
     * @param workId
     * @param model
     * @return
     */
    @RequiresPermissions("sales:order:reply")
    @GetMapping("/replyRead/{workId}")
    public String replyRead(@PathVariable Long workId, Model model) {
        model.addAttribute("workComments", workOrderService.getWorkComment(workId));
        model.addAttribute("workOrder", workOrderService.getByKey(workId));
        return prefix + "/replyRead";
    }

}
